package com.iot08.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.iot08.api.constant.Constant;
import com.iot08.api.service.DeviceService;
import com.iot08.api.utils.ZLOpensslSign;
import com.iot08.api.vo.request.WatchWxSDKSignVO;
import com.iot08.common.entity.app.Device;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.URL;

/**
 * @version 1.0
 * @Description: 腾讯手表微信获取SDK签名
 * @time: 2021/07/23 16:22
 * @author: weichao
 */
@RestController
@RequestMapping("getway")
@Slf4j
public class WatchWXSDKSignController {

    @Resource
    private DeviceService deviceService;

    @Value("${TXZLProduct_id}")
    private String TXZLProduct_id;
    @Value("${TXZLKeyVersion}")
    private String TXZLKeyVersion;
    @Value("${TXZLDevSignFilePath}")
    private String TXZLDevSignFilePath;
    //私钥地址
    @Value("${TXZLPriv_keyPath}")
    private String TXZLPriv_keyPath;
    //公钥地址
    @Value("${TXZLPub_keyPath:}")
    private String TXZLPub_keyPath;

    @Value("${TXZLShellFilePath}")
    private String TXZLShellFilePath;

    @Value("${TXZL_WX_QIMIWATCHKEY}")
    private String TXZL_WX_QIMIWATCHKEY;


    /**
     * 腾讯手表微信获取SDK签名
     *
     * @param vo 集合参数
     * @time: 2021/07/23 16:30
     * @author: weichao
     * @version 1.0
     */
    @PostMapping("watchWxSDKSign")
    public ResponseMap watchWxSDKSign(WatchWxSDKSignVO vo,
                                      BindingResult bindingResult) {

        JSONObject resOB = new JSONObject();
        String key = DigestUtils.md5Hex(TXZL_WX_QIMIWATCHKEY + vo.getTimestamp()).toUpperCase();
        if (!key.equals(vo.getSign().toUpperCase())) {
            log.info("认证失败.sign值错误, sign:{}, timestamp: {}", vo.getSign(), vo.getTimestamp());
            return ResponseMap.fail("认证失败.sign值错误");
        }

        Device devOB = deviceService.findById(vo.getDeviceId());
        if (devOB == null){
            return ResponseMap.fail(ResponseEnum.STATUS2001.getCode(), ResponseEnum.STATUS2001.getMsg() + vo.getDeviceId());
        }
        String deviceSignature = devOB.getDeviceSignature();
        boolean needReSignature = false;
        if (deviceSignature != null){
            //验证一下是否能验证通过, 如果验证不同过,需要重新生成.
            resOB.put("DeviceSignature", deviceSignature);
            boolean res = ZLOpensslSign.VerifyEcdsaSign(TXZLProduct_id, vo.getDeviceId(), TXZLPub_keyPath, TXZLDevSignFilePath + vo.getDeviceId() + "-WXSDKSign");
            if (!res) {
                needReSignature = true;
            }
        } else {
            needReSignature = true;
        }
        if (needReSignature) {
            log.info("私钥路径: priv_keyUrl.getPath():{}",TXZLPriv_keyPath);
            String devSign = ZLOpensslSign.linuxGenEcdsaSign(TXZLShellFilePath, TXZLProduct_id, vo.getDeviceId(),TXZLPriv_keyPath,TXZLDevSignFilePath+vo.getDeviceId()+"-WXSDKSign");
            if(StringUtils.isNotBlank(devSign)){
                resOB.put("DeviceSignature", devSign);
                devOB.setDeviceSignature(devSign);
                deviceService.save(devOB);
            }
        }
        resOB.put("ProductId", Integer.valueOf(TXZLProduct_id));
        resOB.put("KeyVersion", Integer.valueOf(TXZLKeyVersion));
        resOB.put("DeviceId", vo.getDeviceId());

        return ResponseMap.success(resOB);
    }

    public static void main(String[] args){
        WatchWXSDKSignController temp = new WatchWXSDKSignController();

        URL priv_keyUrl = temp.getClass().getClassLoader().getResource("config/TXZL_watchPrivKey/priv_key");
        log.info("priv_keyUrl.getPath():{}",priv_keyUrl.getPath());
    }

}
